-- set_random_main_target
--
local import = import
local utils = utils
local trace = trace
local math = math
---@type behavior_ret
local bret = import("bt/bt_plugin/behavior3/behavior_ret")
---@type main_target
local main_target = import("bt/bt_framework/func/main_target")

local M = {
    name = "set_random_main_target",
    type = "Action",
    desc = "随机选择一个主目标",
    args = {

    },
    output = { "随机目标列表?" }
}

function M.run(node, env, value)
    -- node.args.str
    local owner = env.owner
    local weightConfig = owner.curMainTargetWeightConfig
    if not weightConfig or table.is_empty(weightConfig) then
        trace.log_trace('没有权重配置')
        return bret.FAIL
    end
    local cfg = node.args
    local needFilterLastMainTarget = cfg.needFilterLastMainTarget
    local lastMainTarget = owner.lastMainTarget
    local res = nil
    local resIndex = -1
    -- 目标列表中有目标时
    local tmpArr = {}
    local maxValue = 0
    for _, v in ipairs(weightConfig) do
        maxValue = maxValue + v.randomWeight
    end
    -- 通过权重随机一个目标
    math.randomseed(os.clock() + os.time())
    local randomVal = math.random(1, maxValue)
    local nextRandom = 0
    for i, v in ipairs(weightConfig) do
        if randomVal > nextRandom and randomVal <= v.randomWeight + nextRandom then
            res = v
            resIndex = i
            break
        end
        nextRandom = nextRandom + v.randomWeight
    end
    if not res then
        trace.log_trace('设置随机目标失败')
        return bret.FAIL
    end

    if res then
        local ret = {}
        if res.arr then
            ret = res.arr;
        else
            table.insert(ret, res)
        end
        table.remove(weightConfig, resIndex)
        return bret.SUCCESS, ret
    else
        trace.log_trace('随机目标为空')
    end
    return bret.FAIL
end

return M
